package idv.arthur.work;

import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * Servlet implementation class FileUpload
 */
//@WebServlet(urlPatterns = { "/FileUpload" })
public class FileUpload extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public FileUpload() {
		super();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		
		Widgets wid = new Widgets();
		Connection conn = wid.getConn(true);
		PreparedStatement ps = null;
		ResultSet rs = null;
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		
		int ver = 0;

		String returnResult = "";
		DiskFileItemFactory factory = new DiskFileItemFactory();

		ServletFileUpload upload = new ServletFileUpload(factory);
		try {
			if (isMultipart) {
				List items = upload.parseRequest(request);
				Iterator iter = items.iterator();
				FileItem tmpItem = null;
				
				while (iter.hasNext()) {
					FileItem item = (FileItem) iter.next();
					if (item.isFormField()) {
						String name = item.getFieldName();
						String value = item.getString();
						if ("loginUser".equalsIgnoreCase(name)){
							loginUser = value;
						}
						if ("tpid".equalsIgnoreCase(name)){
							tpid = Integer.parseInt(value);
						}
						if ("mrid".equalsIgnoreCase(name)){
							mrid = value;
						}
					}
				}
				iter = items.iterator();
				
				while (iter.hasNext()) {
					FileItem item = (FileItem) iter.next();
					if (!item.isFormField() && !"".equalsIgnoreCase(item.getName().trim())) {
						/** 目前類型是檔案 **/

						/** 先寫入DB **/
						ver = wid.getVer(tpid, mrid, conn, ps, rs);
						String strSQL = "INSERT INTO tms_mrfileupload (sn,tpid,mrid,ver,ori_filename,creator,createdTime) VALUES (NULL,?,?,?,?,?,?)";
						String fileName = item.getName();

						ps = conn.prepareStatement(strSQL);
						ps.setInt(1, tpid); // 測試計畫案序號
						ps.setString(2, mrid); // 測試項目序號
						ps.setInt(3, ver); // 目前的版本號
						ps.setString(4, fileName); // 原本檔案上傳時的名稱
						ps.setString(5, loginUser); // 上傳人員
						ps.setTimestamp(6, wid.currentTimeStamp()); // 上傳的時間點
						ps.execute();

						/** 開始儲存檔案 **/
						int currentSN = wid.getFileUploadSN(conn, ps, rs);
						
						File uploadedFile = new File(saveDirectory + String.valueOf(currentSN));
						tmpItem = item;
						tmpItem.write(uploadedFile);

						returnResult += "\n";
						returnResult += "fileName：";
						returnResult += fileName;
						returnResult += "\n";
						returnResult += "\n";
					}
				}

			}
			System.out.println(returnResult);
		} catch (SQLException e) {
			returnResult = wid.keepErrorMes(conn, ps, e, "", true);
		} catch (FileUploadException e) {
			returnResult = wid.keepErrorMes(conn, ps, e, "", true);
		} catch (Exception e) {
			returnResult = wid.keepErrorMes(conn, ps, e, "", true);
		} finally {
			try {
				if (rs != null) { rs.close(); }
				if (ps != null) { ps.close(); }
				if (conn != null) { conn.close(); }
			} catch (SQLException e) {
				returnResult = e.toString();
			}
		}

		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		response.getWriter().write(returnResult);
	}
	
	//final String saveDirectory = "C:\\";
	final String saveDirectory = "/disk3/fileupload/";
	String loginUser = "";
	int tpid = 0;
	String mrid = "";
}